package mv.io;

import mv.wap.Link;
import mv.wap.Page;
import mv.main.MObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.List;

/**
 * Class description...
 *
 * @author mvu
 */
public class FileIO extends MObject {
  private static final String _root = SimpleProperties.getRootFile();
  private static FileIO _instance;

  private FileIO(){}

  public static FileIO getInstance(){
    if(_instance == null) _instance = new FileIO();
    File root = new File(_root);
    if(! root.exists()) root.mkdir();
    return _instance;
  }

  public void save(Page page) throws Exception {
    Set<String> titles = new HashSet<String>();
    savePageAndLinks(page, titles);
  }

  private void savePageAndLinks(Page page, Set<String> titles) throws IOException {
    if(page == null){
      return; 
    }
    if(! titles.contains(page.getTitle())){
      File file = new File(_root, page.getTitle() + ".html");
      BufferedWriter out = new BufferedWriter(new FileWriter(file));
      out.write(page.toHtml());
      titles.add(page.getTitle());
      print("Saved " + file.getAbsolutePath());
      out.close();
      for(Link link : page.getLinks()){
        savePageAndLinks(link.getTarget(), titles);
      }
    }
  }

  public void save(List<Page> pages) throws IOException {
    Set<String> titles = new HashSet<String>();
    for(Page page : pages){
      savePageAndLinks(page, titles);
    }
  }
}
